package com.itheima02.ioc;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.ResourceBundle;

/*
    工厂类: 生产对象
 */
public class ServiceFactory {
    /*
    * 1. 对象用的时候才创建,效率比较低,可以创建好
    * 2. 因为对象太多, 可以放在容器中
    * */
    private static HashMap<String,Object> map = new HashMap<>();

    static{
        try {
            ResourceBundle bundle = ResourceBundle.getBundle("service");

            //批量生产对象: 配置文件中有就创建 , 然后放到容器中
            //获取所有的key并遍历
            Enumeration<String> keys = bundle.getKeys();
            while(keys.hasMoreElements()){
                // key = userService/roleService
                String key = keys.nextElement();
                String value = bundle.getString(key);

                Class<?> clazz = Class.forName(value);
                Object o = clazz.newInstance();
                map.put(key, o);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Object getBean(String key){
        return map.get(key);
    }

}
